package com.faceCaptor.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class HttpUtil {
	
//	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
	
	public final static String HOST="http://47.93.205.45:8080";
//    public final static String HOST = "http://localhost:8080";
//    public final static String HOST="http://manage.aimendian.cn/api";
	
	public final static String ADDUSER="/face/user/add";
	
	public final static String ADDREMARK="/face/remark/add";
	
	public final static String GETREMARKS="/face/remark/get/1?limit=3";
	
	public final static String REMARKHISTORY="/face/remark/get/history/";
    
	public final static String SHOPLOGIN ="/face/login/shopLogin";
	
	public final static String UPDATEUSER="/face/user/update";
	
	public final static String GETUSER="/face/user/get";
    public final static String USER_LIST = "/face/user/list";


    public final static String SAVEVISIT="/face/login/visit";

    public final static String CHECK_UPDATA = "/face/update/check?version=";
    public static final String GROUP = "/face/user/group";

    private static Logger log = Logger.getLogger(HttpUtil.class);

    public static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    private static ExecutorService downloadExcutorService = Executors.newFixedThreadPool(1);;
    public static boolean isCancel;
    private static boolean isDownloading;

    public static String sendGetRequest(String url){
    	
        String str = "";
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("status code:" + statusCode);
                return "";
            }
            HttpEntity entity = response.getEntity();
            str =  EntityUtils.toString(entity, "utf-8");
        } catch (IOException e) {
            log.error("=======get请求出错:{}=======",e);
        }catch(Exception e){
        	log.error(e);
        }finally {
            httpGet.releaseConnection();
        }
        return str;
    }
    
    public static InputStream getCommonFile(String url){
        //从服务器请求文件流，具体代码就不贴了
		HttpPost httpPost = new HttpPost(url);
		HttpResponse response ;
		InputStream inputStream = null;
		try {
			response = httpClient.execute(httpPost);
			inputStream = response.getEntity().getContent();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
        
		
        return inputStream;
        

	}
    
    public static InputStream getFile(String url){
     	 
    	 InputStream iStream=null;
         HttpGet httpGet = new HttpGet(url);
         try {
             HttpResponse response = httpClient.execute(httpGet);

             HttpEntity entity = response.getEntity();
             iStream=entity.getContent();
         } catch (IOException e) {
             log.error("=======get请求出错:{}=======",e);
         }finally {
             httpGet.releaseConnection();
         }
         return iStream;
    }

    //参数封装成对象进行传输
    public static <T> JSONObject postSwtForm(String url,T element){
    	JSONObject jsonObject=null;
    	HttpPost httpPost = new HttpPost(url);
    	httpPost.addHeader("Content-type","application/json; charset=utf-8");
        httpPost.addHeader("Accept", "application/json");
        
    	httpPost.setEntity(new StringEntity(JSONObject.toJSONString(element), Charset.forName("UTF-8")));
//		httpPost.
    	try {
			HttpResponse response = httpClient.execute(httpPost);
			
			HttpEntity httpEntity = response.getEntity();
			String str =EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
//			System.out.println("返回的字符串"+str);
			jsonObject =JSON.parseObject(str);
			
		} catch (ClientProtocolException e) {
    	    log.error(e);
		} catch (IOException e) {
			log.error(e);
		}
		return jsonObject;
    	
    }
    //post的form-data方式提交
    public static String sendPostRequest(String url,Map<String,String> params){
        StringBuffer stringBuffer = new StringBuffer();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
        if(null != params) {
            for (String key : params.keySet()) {
                valuePairs.add(new BasicNameValuePair(key, params.get(key)));
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(valuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            BufferedInputStream bis = new BufferedInputStream(httpEntity.getContent());
            byte [] buffer;
            while (0<bis.read(buffer=new byte[128])){
                stringBuffer.append(new String(buffer,"utf-8"));
            }
        }catch (UnsupportedEncodingException e){
            //数据格式有误
            log.error("=======数据格式出错:{}=======",e);
        }catch (IOException e){
            //请求出错
            log.error("=======post请求出错:{}=======",e);
        }finally {
            httpPost.releaseConnection();
        }
        return stringBuffer.toString();
    }

    //post的raw方式提交
    public static String sendPostRequest(String url,String params){

        StringBuffer stringBuffer = new StringBuffer();

        
        log.info("提交数据:{}"+params);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(params,Charset.forName("UTF-8")));

        try {
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity httpEntity = response.getEntity();
            BufferedInputStream bis = new BufferedInputStream(httpEntity.getContent());
            byte [] buffer;
            while (0<bis.read(buffer=new byte[128])){
                stringBuffer.append(new String(buffer,"utf-8"));
            }

        } catch (IOException e) {
            log.error("=======数据格式出错:{}=======",e);
        }finally {
            httpPost.releaseConnection();
        }
        return stringBuffer.toString();
    }

    /**
     * 取消下载
     */
    public static void cancelDownload() {
        isCancel = true;
    }

    /**
     * 上传进度
     */
    public interface HttpClientDownLoadProgress {
        void onProgress(int progress);
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     * @param progress 进度回调
     */
    public static void download(final String url, final String filePath,
                         final HttpClientDownLoadProgress progress) {
        if (isDownloading) {
            return;
        }
        downloadExcutorService.execute(new Runnable() {

            @Override
            public void run() {
                httpDownloadFile(url, filePath, progress);
            }
        });
    }

    /**
     * 下载文件
     * @param url
     * @param fileName
     * @param progress
     */
    private static void httpDownloadFile(String url, String fileName,
                                  HttpClientDownLoadProgress progress) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            isCancel = false;
            isDownloading = true;
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                HttpEntity httpEntity = response.getEntity();
                long contentLength = httpEntity.getContentLength();
                if (contentLength <= 0) {
                    log.error("下载文件不存在");
                    return;
                }
                InputStream is = httpEntity.getContent();

                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    if (isCancel) {
                        httpGet.abort();
                        isDownloading = false;
                        break;
                    }
                    output.write(buffer, 0, r);
                    totalRead += r;
                    // 回调进度
                    if (progress != null) {
                        progress.onProgress((int) (totalRead * 100 / contentLength));
                    }
                }
                String path = getPath();
                File file = new File(path + "/download", fileName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);
                if (!isCancel) {
                    Runtime rt = Runtime.getRuntime();
                    rt.exec(file.getPath());
                }
            } finally {
                response.close();
                isCancel = false;
                isDownloading = false;
            }
        } catch (Exception e) {
            log.error("下载出错", e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("下载出错", e);
            }
        }
    }

    public static String getPath() {
        String jarPath = System.getProperty("user.dir");
        return jarPath;
    }
}

